package com.offcn.searchweb.controller;

import org.springframework.ui.Model;
import com.offcn.common.entity.Result;
import com.offcn.search.feign.SearchFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("searchweb")
public class SearchwebController {

    @Autowired
    private SearchFeign searchFeign;

    @GetMapping("show")
    public String show(@RequestParam(required = false) Map<String,String>searchMap, Model model){
        Result result = searchFeign.search(searchMap);
        Map<String,Object> map = (Map<String, Object>) result.getData();
        model.addAttribute("map",map);
        model.addAttribute("searchMap",searchMap);
        model.addAttribute("url",getUrl(searchMap));
        return "search.html";
    }

    private String getUrl(Map<String,String>searchMap){
        // /searchweb/show?keywords=三星&category=手机&brand=三星&spec_网络=16G
        String url = "/searchweb/show?";
        if(searchMap != null && searchMap.size() > 0) {
            for (String key : searchMap.keySet()) {
                if("sortFeild".equals(key)){
                    continue;
                }
                if("sortType".equals(key)){
                    continue;
                }
                if("pageNo".equals(key)){
                    continue;
                }
                String value = searchMap.get(key);
                url += "&" + key + "=" + value;
            }
        }
        return url;
    }
}
